<template>
  <div>
    <a-alert type="warning" show-icon style="margin-bottom: 18px">
      <template #description>
        提供实时通讯系列对接接口，专注业务开发。
        <a
          href="https://doc.21ds.cn/detail?doc=4731341806141859/4925709230745034"
          target="_blank"
          rel="noopener noreferrer"
          >对接文档</a
        >
      </template>
    </a-alert>
    <div class="table-page-search-wrapper">
      <a-row type="flex" justify="space-between" align="middle">
        <a-col :span="16">
          <a-form layout="inline" :model="listQuery">
            <a-form-item label="搜索项">
              <a-input v-model:value="listQuery.title" placeholder="输入名称/AppId搜索..." />
            </a-form-item>
            <a-form-item>
              <a-button type="primary" @click="searchSubmit"> 搜索 </a-button>
            </a-form-item>
          </a-form>
        </a-col>
        <a-col :span="8">
          <div style="margin-right: 0px; float: right; display: flex; align-item: center">
            <a-tooltip placement="top">
              <template #title>
                <span>刷新列表</span>
              </template>
              <a-button @click="reloadList">
                <template #icon>
                  <SyncOutlined />
                </template>
              </a-button>
            </a-tooltip>
            <a-button
              v-permission="{ action: 'socket_io_add' }"
              type="primary"
              style="margin-left: 12px"
              @click="socket_io_add"
            >
              <template #icon>
                <PlusOutlined />
              </template>
              新增实时通讯
            </a-button>
          </div>
        </a-col>
      </a-row>
    </div>
    <a-table
      :columns="columns"
      :rowKey="(record) => record._id"
      :dataSource="dataList.data"
      :loading="loading"
      :pagination="pagination"
      @change="handleTableChange"
    >
      <template #status="{ text: record }">
        <a-tag v-if="record == 1" color="green">启用</a-tag>
        <a-tag v-if="record == 0">未启用</a-tag>
      </template>
      <template #action="{ text: record }">
        <a v-permission="{ action: 'socket_io_add' }" @click="socket_io_edit(record)">
          <EditOutlined /> 编辑
        </a>
        <!-- <a-divider v-permission="{ action: 'socket_io_auto_reply' }" type="vertical" />
        <a v-permission="{ action: 'socket_io_auto_reply' }" @click="socket_io_auto_reply(record)">
          自动回复
        </a>
        <a-divider v-permission="{ action: 'socket_io_media' }" type="vertical" />
        <a v-permission="{ action: 'socket_io_media' }" @click="socket_io_media(record)"> 素材 </a>
        <a-divider v-permission="{ action: 'socket_io_menu' }" type="vertical" />
        <a v-permission="{ action: 'socket_io_menu' }" @click="socket_io_menu(record)"> 菜单 </a>
        <a-divider v-permission="{ action: 'socket_io_oauth' }" type="vertical" />
        <a v-permission="{ action: 'socket_io_oauth' }" @click="socket_io_oauth(record)"> 网页授权 </a> -->
        <a-divider v-permission="{ action: 'socket_io_del' }" type="vertical" />
        <a
          v-permission="{ action: 'socket_io_del' }"
          style="color: red"
          @click="socket_io_delete(record)"
        >
          <DeleteOutlined /> 删除
        </a>
      </template>
    </a-table>
    <a-drawer
      width="45%"
      title="实时通讯详情"
      placement="right"
      :open="drawerShow"
      @close="
        () => {
          drawerShow = false
        }
      "
    >
      <template #extra>
        <a-button
          style="margin-right: 8px"
          @click="
            () => {
              drawerShow = false
            }
          "
          >取消</a-button
        >
        <a-button type="primary" @click="addItem">提交</a-button>
      </template>
      <a-form
        ref="formRef"
        :model="FormState"
        :rules="FormRule"
        :labelCol="labelCol"
        :wrapperCol="wrapperCol"
      >
        <a-form-item label="名称" has-feedback required name="title">
          <a-input v-model:value="FormState.title" placeholder="请输入名称" />
        </a-form-item>
        <a-form-item has-feedback required label="SecretKey" name="server_secret">
          <a-input-search
            v-model:value="FormState.server_secret"
            placeholder="点击右侧“获取密钥”按钮进行获取"
            enter-button="获取密钥"
            @search="resetSecret"
          />
        </a-form-item>
        <a-form-item has-feedback required label="SecretKey(Md5)">
          <a-input
            v-model:value="FormState.server_secret_md5"
            placeholder="获取SecretKey后自动生成"
            readonly
          />
        </a-form-item>
        <a-form-item label="状态" has-feedback required name="status">
          <a-radio-group v-model:value="FormState.status" name="status">
            <a-radio :key="1" :value="1">启用</a-radio>
            <a-radio :key="0" :value="0">不启用</a-radio>
          </a-radio-group>
        </a-form-item>
      </a-form>
    </a-drawer>
  </div>
</template>

<script lang="ts">
import { defineComponent, reactive, toRefs, onMounted, ref, toRaw, watch } from 'vue'
import {
  Row,
  Col,
  Modal,
  Divider,
  Drawer,
  Card,
  Tooltip,
  Statistic,
  RadioGroup,
  RangePicker,
  Tag,
  ImagePreviewGroup,
  Image,
  Upload,
  Empty,
  Pagination,
  Spin
} from 'ant-design-vue'
import {
  SyncOutlined,
  PlusOutlined,
  EditOutlined,
  DeleteOutlined,
  ExclamationCircleOutlined,
  DownOutlined,
  CopyOutlined,
  QuestionCircleOutlined,
  LoadingOutlined
} from '@ant-design/icons-vue'
import { requestSuccess, requestFailed } from '@/utils/feedback'
import { delArtItem, getItemList, editData } from '@/api/socket.io'
import { useRouter } from 'vue-router'
import { copyText, randomString } from '@/utils/common'
import CryptoJS from 'crypto-js'

export default defineComponent({
  name: 'MpList',
  components: {
    Empty,
    SyncOutlined,
    PlusOutlined,
    EditOutlined,
    ExclamationCircleOutlined,
    DownOutlined,
    QuestionCircleOutlined,
    CopyOutlined,
    LoadingOutlined,
    DeleteOutlined,
    [Tag.name]: Tag,
    [Row.name]: Row,
    [Spin.name]: Spin,
    [Card.name]: Card,
    [Upload.name]: Upload,
    [ImagePreviewGroup.name]: ImagePreviewGroup,
    [Image.name]: Image,
    [Tooltip.name]: Tooltip,
    [RadioGroup.name]: RadioGroup,
    [RangePicker.name]: RangePicker,
    [Divider.name]: Divider,
    [Statistic.name]: Statistic,
    [Drawer.name]: Drawer,
    [Pagination.name]: Pagination,
    [Col.name]: Col
  },
  setup() {
    const formRef = ref()
    const router = useRouter()
    const state = reactive<any>({
      loading: true,
      drawerShow: false,
      dataList: [],
      select_mw_id: '',
      activeKey: ref('1'),
      listQuery: {
        pageNo: 1,
        pageSize: 15,
        title: ''
      },
      pagination: {
        pageSizeOptions: ['15', '30', '50'],
        showSizeChanger: true,
        total: 1,
        showTotal: (total) => `共 ${total} 条数据`,
        pageSize: 15,
        current: 1
      },
      labelCol: {
        xs: { span: 24 },
        sm: { span: 3 }
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 20 }
      },
      columns: [
        {
          title: 'SocketId',
          dataIndex: '_id'
        },
        {
          title: '名称',
          dataIndex: 'title'
        },
        {
          title: '状态',
          dataIndex: 'status',
          slots: { customRender: 'status' }
        },
        {
          title: '创建时间',
          dataIndex: 'create_time'
        },
        {
          title: '操作',
          slots: { customRender: 'action' }
        }
      ]
    })
    onMounted(() => {
      getDataList()
    })
    const FormState = reactive<any>({
      _id: '',
      title: '',
      server_secret_md5: '',
      server_secret: ''
    })
    watch(
      () => FormState.server_secret,
      () => {
        FormState.server_secret_md5 = CryptoJS.MD5(FormState.server_secret).toString()
      }
    )
    const FormRule = {
      title: [{ required: true, message: '请输入标题', trigger: ['blur', 'change'] }],
      server_secret: [{ required: true, message: '请生成SecretKey', trigger: ['blur', 'change'] }]
    }

    function handleTableChange(e) {
      state.loading = true
      state.pagination.pageSize = e.pageSize
      state.listQuery.pageSize = e.pageSize
      state.listQuery.pageNo = e.current
      state.pagination.current = e.current
      getDataList()
    }
    function resetSecret() {
      FormState.server_secret = randomString(64)
    }
    function reloadList() {
      state.loading = true
      state.listQuery.pageNo = 1
      state.pagination.current = 1
      getDataList()
    }
    function copyData(txt) {
      copyText(txt)
    }

    function searchSubmit() {
      state.loading = true
      state.listQuery.pageNo = 1
      state.pagination.current = 1
      getDataList()
    }
    function socket_io_edit(res) {
      for (let item in FormState) {
        FormState[item] = ''
      }
      for (let item in res) {
        FormState[item] = res[item]
      }
      state.drawerShow = true
    }
    function socket_io_add() {
      for (let item in FormState) {
        FormState[item] = ''
      }
      state.drawerShow = true
    }
    function getDataList() {
      getItemList(state.listQuery).then((res) => {
        state.loading = false
        state.dataList = res
        state.pagination.total = res.totalCount
      })
    }
    const addItem = () => {
      formRef.value
        .validate()
        .then(() => {
          editData(toRaw(FormState)).then((res) => {
            if (res.code === 200) {
              requestSuccess(res)
              formRef.value.resetFields()
              state.loading = true
              state.drawerShow = false
              reloadList()
            } else {
              requestFailed(res)
            }
          })
        })
        .catch(() => {
          return false
        })
    }
    function socket_io_delete(data) {
      Modal.confirm({
        title: '确认删除此实时通讯?',
        content: '【' + data.title + '】',
        okType: 'danger',
        okText: '确认删除',
        onOk() {
          delArtItem({ id: data._id }).then((res) => {
            if (res.code === 200) {
              state.loading = true
              getDataList()
              requestSuccess(res)
            } else {
              requestFailed(res)
            }
          })
        }
      })
    }
    return {
      ...toRefs(state),
      handleTableChange,
      reloadList,
      resetSecret,
      searchSubmit,
      socket_io_delete,
      formRef,
      socket_io_add,
      copyData,
      FormState,
      socket_io_edit,
      addItem,
      FormRule,
      router,
      getDataList
    }
  }
})
</script>

<style>
.imgListDiv .ant-image-img {
  width: 200px;
  height: 200px;
}

.imgListDiv .ant-image {
  margin: 0px 15px 15px 0px;
}
.imgCheckBox {
  position: absolute;
  z-index: 99;
}
</style>
